package prolog
import prolog.terms._
import prolog.io._

object Main {
  def main(args: Array[String]): Unit = {

    //Tests.utest
    //println("ok")
    //Tests.ctest
    //Tests.ptest
    //Tests.gutest
    //Tests.ltest
    //Tests.btest

    toplevel(args.toList)

  }

  def toplevel(topgoals: List[String]) {

    def printvar(x: (String, Term)) =
      println(x._1 + "=" + x._2)

    val parser = new TermParser()
    val prog: Prog = new Prog()

    topgoals.foreach { x =>
      val gv = parser.parseWithVars(x)
      if (null != gv) {
        prog.set_query(gv._1)
        var more = true
        while (more) {
          val answer = prog.getElement()
          if (answer.eq(null)) more = false
          else
            gv._2.foreach(printvar)
        }
      }
    }

    var goalWithVars = parser.parseWithVars("true")

    while (!goalWithVars.eq(null)) {
      goalWithVars = parser.readGoal()

      if (!goalWithVars.eq(null)) {
        val goal = goalWithVars._1
        val vars = goalWithVars._2
        prog.set_query(goal)
        var more = true
        while (more) {
          val answer = prog.getElement()
          if (answer.eq(null)) more = false
          else {
            if (vars.isEmpty) println("yes.")
            else {
              vars.foreach(printvar)
              println(";")
            }
          }
        }
        println("no (more) answers\n")
      }
    }
    println("\nProlog execution halted\n")
  }
}
